﻿using System.Collections;
using UnityEngine;

public class HealthBarEasing : MonoBehaviour
{
    public UISprite healthBar; // 在Inspector中关联血条Sprite
    private float currentFillAmount = 1f; // 当前显示值
    private float targetFillAmount = 1f; // 目标值
    public float easingDuration = 0.5f; // 缓动持续时间

    void Start()
    {
        currentFillAmount = healthBar.fillAmount;
        targetFillAmount = currentFillAmount;
    }

    // 设置目标血量 (0.0 - 1.0)
    public void SetTargetHealth(float targetHealth)
    {
        targetFillAmount = Mathf.Clamp01(targetHealth);
        StopAllCoroutines(); // 停止之前的缓动
        StartCoroutine(EaseToTarget());
    }

    private IEnumerator EaseToTarget()
    {
        float startAmount = currentFillAmount;
        float endAmount = targetFillAmount;
        float elapsedTime = 0f;

        while (elapsedTime < easingDuration)
        {
            elapsedTime += Time.deltaTime;
            float t = Mathf.Clamp01(elapsedTime / easingDuration);

            // 使用缓动函数让变化更平滑
            t = 1f - Mathf.Pow(1f - t, 3); // 三次方缓动

            currentFillAmount = Mathf.Lerp(startAmount, endAmount, t);
            GetComponent<UISprite>().fillAmount = currentFillAmount;

            yield return null;
        }

        currentFillAmount = endAmount;
        GetComponent<UISprite>().fillAmount = currentFillAmount;
    }

    // 测试用：按A减血，按D加血
    void Update()
    {
        SetTargetHealth(healthBar.fillAmount);
    }
}